/**
 * 增量更新服务
 * 负责检测数据变化并实现增量更新功能
 */

import { cacheManager } from './cacheManager'

// 默认的STRATZ API token（作为备用）
const DEFAULT_STRATZ_API_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJTdWJqZWN0IjoiNTYyN2NkNDItMjg2ZC00YTVlLTk1YzEtNWMyOGZiZjA2MTE2IiwiU3RlYW1JZCI6IjEwMTE3NDEzNyIsIkFQSVVzZXIiOiJ0cnVlIiwibmJmIjoxNzU4NzYyNjMwLCJleHAiOjE3OTAyOTg2MzAsImlhdCI6MTc1ODc2MjYzMCwiaXNzIjoiaHR0cHM6Ly9hcGkuc3RyYXR6LmNvbSJ9.x4MCCqqhuCPp9l3dpZv8r4f7X8b4lfn9xcBUi16kx98'

// 获取用户设置的API key或使用默认值
const getStratzApiToken = (): string => {
  const userApiKey = localStorage.getItem('stratz_api_key');
  return userApiKey && userApiKey.trim() ? userApiKey.trim() : DEFAULT_STRATZ_API_TOKEN;
}

interface UpdateCheckResult {
  hasUpdates: boolean
  lastModified?: string
  etag?: string
  matchCount?: number
  lastMatchDateTime?: string
}

interface IncrementalUpdateOptions {
  forceUpdate?: boolean
  checkInterval?: number // 检查间隔（毫秒）
}

class IncrementalUpdater {
  private updateTimers: Map<number, NodeJS.Timeout> = new Map()
  private lastCheckTimes: Map<string, number> = new Map()
  
  /**
   * STRATZ API GraphQL 查询方法 - 与 api.ts 保持一致
   */
  private async fetchStratzAPI(query: string, variables?: any): Promise<any> {
    try {
      const apiToken = getStratzApiToken();
      const response = await fetch('https://api.stratz.com/graphql', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiToken}`,
          'User-Agent': 'STRATZ_API'
        },
        body: JSON.stringify({
          query,
          variables
        })
      })

      if (!response.ok) {
        throw new Error(`STRATZ API请求失败: ${response.status} ${response.statusText}`)
      }

      const data = await response.json()
      
      if (data.errors) {
        throw new Error(`STRATZ API错误: ${data.errors.map((e: any) => e.message).join(', ')}`)
      }

      return data.data
    } catch (error) {
      console.error('STRATZ API请求失败:', error)
      throw error
    }
  }
  
  /**
   * 检查联赛详情是否有更新
   */
  /**
   * 检查联赛详情是否有更新 - 使用 GraphQL API 获取比赛总数
   */
  async checkLeagueDetailUpdates(leagueId: number): Promise<UpdateCheckResult> {
    try {
      console.log(`incrementalUpdater - 开始检查联赛 ${leagueId} 的详情更新`)
      
      // 使用与 api.ts 相同的 fetchStratzAPI 方法
      const query = `
        query GetLeagueStats($id: Int!) {
          league(id: $id) {
            id
            displayName
            stats {
              matchCount
            }
            lastMatchDateTime
          }
        }
      `
      
      console.log(`incrementalUpdater - 发送GraphQL查询:`, { query, variables: { id: leagueId } })
      const result = await this.fetchStratzAPI(query, { id: leagueId })
      console.log(`incrementalUpdater - GraphQL查询结果:`, result)
      
      if (!result || !result.league) {
        console.warn(`incrementalUpdater - League ${leagueId} not found or no data returned`)
        return { hasUpdates: false }
      }
      
      const league = result.league
      const currentMatchCount = league.stats?.matchCount || 0
      const lastMatchDateTime = league.lastMatchDateTime
      
      console.log(`incrementalUpdater - 解析结果: matchCount=${currentMatchCount}, lastMatchDateTime=${lastMatchDateTime}`)
      
      // 获取缓存的比赛数量
      const cachedMatchCount = cacheManager.getCachedMatchCount(leagueId)
      
      console.log(`incrementalUpdater - League ${leagueId} - 缓存比赛数: ${cachedMatchCount}, 当前比赛数: ${currentMatchCount}`)
      
      // 检查是否有新比赛
      const hasUpdates = cachedMatchCount !== null && currentMatchCount > cachedMatchCount
      
      return {
        hasUpdates,
        matchCount: currentMatchCount,
        lastMatchDateTime: lastMatchDateTime
      }
    } catch (error) {
      console.error('incrementalUpdater - Error checking league detail updates:', error)
      // 重新抛出认证错误和 500 错误以便上层处理
      if (error instanceof Error && (error.message.includes('认证失败') || error.message.includes('500'))) {
        throw error
      }
      return { hasUpdates: false }
    }
  }
  
  /**
   * 检查联赛比赛是否有更新 - 使用 GraphQL API 获取比赛总数
   */
  async checkLeagueMatchesUpdates(leagueId: number): Promise<UpdateCheckResult> {
    try {
      // 使用与 api.ts 相同的 fetchStratzAPI 方法
      const query = `
        query GetLeagueMatchStats($id: Int!) {
          league(id: $id) {
            id
            stats {
              matchCount
            }
            lastMatchDateTime
          }
        }
      `
      
      const result = await this.fetchStratzAPI(query, { id: leagueId })
      
      if (!result || !result.league) {
        console.warn(`League ${leagueId} not found or no data returned`)
        return { hasUpdates: false }
      }
      
      const league = result.league
      const currentMatchCount = league.stats?.matchCount || 0
      const lastMatchDateTime = league.lastMatchDateTime
      
      // 获取缓存的比赛数量
      const cachedMatchCount = cacheManager.getCachedMatchCount(leagueId)
      
      console.log(`League ${leagueId} matches - 缓存比赛数: ${cachedMatchCount}, 当前比赛数: ${currentMatchCount}`)
      
      // 检查是否有新比赛
      const hasUpdates = cachedMatchCount !== null && currentMatchCount > cachedMatchCount
      
      return {
        hasUpdates,
        matchCount: currentMatchCount,
        lastMatchDateTime: lastMatchDateTime
      }
    } catch (error) {
      console.error('Error checking league matches updates:', error)
      // 重新抛出认证错误和 500 错误以便上层处理
      if (error instanceof Error && (error.message.includes('认证失败') || error.message.includes('500'))) {
        throw error
      }
      return { hasUpdates: false }
    }
  }
  
  /**
   * 启动自动更新检查
   */
  startAutoUpdate(leagueId: number, options: IncrementalUpdateOptions = {}) {
    const { checkInterval = 5 * 60 * 1000 } = options // 默认5分钟检查一次
    
    // 清除现有的定时器
    this.stopAutoUpdate(leagueId)
    
    const timer = setInterval(async () => {
      try {
        // 检查联赛详情更新
        const detailUpdate = await this.checkLeagueDetailUpdates(leagueId)
        if (detailUpdate.hasUpdates) {
          console.log(`League ${leagueId} detail has updates`)
          // 触发更新事件
          this.emitUpdateEvent('detail', leagueId, detailUpdate)
        }
        
        // 检查比赛更新
        const matchesUpdate = await this.checkLeagueMatchesUpdates(leagueId)
        if (matchesUpdate.hasUpdates) {
          console.log(`League ${leagueId} matches have updates`)
          this.emitUpdateEvent('matches', leagueId, matchesUpdate)
        }
        
        // 更新最后检查时间
        this.lastCheckTimes.set(`${leagueId}`, Date.now())
      } catch (error) {
        console.error(`Error in auto update for league ${leagueId}:`, error)
        // 如果是网络错误或API错误，暂停一段时间后再继续
        if (error instanceof Error && (error.message.includes('500') || error.message.includes('network'))) {
          console.log(`API error detected, pausing auto update for league ${leagueId} for 10 minutes`)
          this.stopAutoUpdate(leagueId)
          // 10分钟后重新启动
          setTimeout(() => {
            console.log(`Restarting auto update for league ${leagueId}`)
            this.startAutoUpdate(leagueId, options)
          }, 10 * 60 * 1000)
        }
      }
    }, checkInterval)
    
    this.updateTimers.set(leagueId, timer)
  }
  
  /**
   * 停止自动更新检查
   */
  stopAutoUpdate(leagueId: number) {
    const timer = this.updateTimers.get(leagueId)
    if (timer) {
      clearInterval(timer)
      this.updateTimers.delete(leagueId)
    }
  }
  
  /**
   * 停止所有自动更新
   */
  stopAllAutoUpdates() {
    this.updateTimers.forEach((timer) => clearInterval(timer))
    this.updateTimers.clear()
  }
  
  /**
   * 触发更新事件
   */
  private emitUpdateEvent(type: 'detail' | 'matches' | 'ranking', leagueId: number, updateInfo: UpdateCheckResult) {
    // 创建自定义事件
    const event = new CustomEvent('leagueDataUpdate', {
      detail: {
        type,
        leagueId,
        updateInfo
      }
    })
    
    // 分发事件
    window.dispatchEvent(event)
  }
  
  /**
   * 获取最后检查时间
   */
  getLastCheckTime(leagueId: number): number | undefined {
    return this.lastCheckTimes.get(`${leagueId}`)
  }
  
  /**
   * 清理资源
   */
  cleanup() {
    this.stopAllAutoUpdates()
    this.lastCheckTimes.clear()
  }
}

// 创建单例实例
export const incrementalUpdater = new IncrementalUpdater()

// 在页面卸载时清理资源
if (typeof window !== 'undefined') {
  window.addEventListener('beforeunload', () => {
    incrementalUpdater.cleanup()
  })
}